<template>
  <div class="app-container">
    <el-row>
      <el-descriptions title="角色基本信息" direction="vertical" :column="4" border>
        <el-descriptions-item label="角色名称">{{ rolename }}</el-descriptions-item>
        <el-descriptions-item label="资源列表">
          <template v-if="rolename === 'admin'">
            <el-tag v-for="role in role.resources" :key="role" class="margin-left margin-top" size="small">{{ role }}</el-tag>
          </template>
          <template v-else>
            <el-tag v-for="role in role.resources" :key="role" closable class="margin-left margin-top" size="small" @close="delResource(role)">{{ role }}</el-tag>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="组织列表">
          <template v-if="rolename === 'admin'">
            <el-tag v-for="group in role.groups" :key="group" class="margin-left margin-top" size="small">{{ group }}</el-tag>
          </template>
          <template v-else>
            <el-tag v-for="group in role.groups" :key="group" closable class="margin-left margin-top" size="small" @close="delGroup(group)">{{ group }}</el-tag>
          </template>
        </el-descriptions-item>
      </el-descriptions>
    </el-row>

    <el-row class="">
      <div class="margin-bottom margin-top"><b>可访问资源</b></div>
      <el-tree ref="accessResourceTree" :data="accessResources" node-key="id" />
    </el-row>
  </div>
</template>

<script>
import security from '@/api/security'

export default {
  name: 'role_detail',
  data() {
    return {
      rolename: null,
      accessResources: [],
      role: { toolRole: {}},
      roleExtend: {
        grantGroups: [],
        grantResources: []
      }
    }
  },
  mounted() {
    this.rolename = this.$route.query.rolename

    // 加载角色详细信息
    security.queryRole(this.rolename).then(res => {
      this.role = res.data
    })

    this.reloadAccessResources()
  },
  methods: {
    reloadAccessResources() {
      // 加载角色可访问资源信息
      security.queryRoleAccessResources(this.rolename).then(res => {
        this.accessResources = res.data
      })
    },
    delResource(tag) {
      this.role.resources.splice(this.role.resources.indexOf(tag), 1)
      security.roleGrantResources(this.rolename, this.role.resources.join(',')).then(res => {
        this.reloadAccessResources()
      })
    },
    delGroup(tag) {
      this.role.groups.splice(this.role.groups.indexOf(tag), 1)
      security.roleGrantGroups(this.rolename, this.role.groups.join(',')).then(res => {
        // 不需要重新加载资源, 删除角色分组并不能影响资源
      })
    }
  }
}
</script>


